{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[29054, 17002, 17002, 17002, 17002, 29188, 29188, 29188, 29188,\n",
       "         29188,  4369,  4369,  4369,  4369,  4369, 26533, 26533, 26533,\n",
       "         26533, 26533, 26533, 15700, 15700, 23752, 23752, 23752, 23752,\n",
       "         23752, 17901, 17901, 17901, 14067, 14067,  4322,  4322,  4322,\n",
       "          4322,  4322,  4322,  4322,  4322,  4322,  4322,  4322,  4322,\n",
       "          4322,  4322,  4322, 27402,  4322,  4322,  4322,  4322, 26355,\n",
       "          8794,  4322,  4322,  4322,  4322,  4322,  4322,  4322, 26355,\n",
       "          4322, 26355,  4322, 26355,  4322,  4322,  4322,  4322, 26355],\n",
       "        [21304, 11233, 11233,   310,   310,   310,   310,  5081,  5081,\n",
       "          5081,  5081, 10446, 10446, 10446,  2600,  2600,  2600, 31169,\n",
       "         31169, 31169,  2008,  2008,  2008,  2008, 28528, 28528, 25165,\n",
       "         25165, 25165, 25165, 25165, 25165, 25165, 31786, 31786, 31786,\n",
       "         20197, 20197, 20197, 30103, 30103, 30103, 30103, 30103, 30103,\n",
       "         19837, 19837, 19837, 19370, 19370, 19370, 19370, 19370, 19370,\n",
       "         19370, 19370, 30038, 30038, 30038, 30038, 30038,  7650,  7650,\n",
       "          7650, 12404, 12404, 12404, 12404, 11773, 11773, 11773, 22618],\n",
       "        [21904, 30738, 12727, 12727, 12727, 21904, 15048, 15048, 15048,\n",
       "         15048, 15048, 15048, 19380, 19380, 19380, 24681, 19877, 19877,\n",
       "         19877, 19877, 19877, 27423, 27423, 19380, 19380, 19380, 19380,\n",
       "         19380, 19380, 19380, 20462, 20462, 20462, 20462, 20462, 10701,\n",
       "         10701, 10701, 10701, 10701, 10701, 29174, 29174, 29174, 13367,\n",
       "         13367, 13367, 13367, 13367, 22744, 22744, 28435, 28435, 28435,\n",
       "         19869, 19869, 19869, 19869, 19869, 18273,  5522,  3681,  3681,\n",
       "          3681, 15420, 15420,  9093, 16951, 16951, 16951, 16397, 16397],\n",
       "        [29150, 29150, 29150, 29150, 30315, 29150, 30315, 30315, 10361,\n",
       "         10361, 10361, 10361, 11234, 11234, 11234, 11234, 11234, 11234,\n",
       "         15361, 15361, 15361, 15361, 15361, 15361, 23738, 23738, 23738,\n",
       "         23738,  7933,  7933, 15460,  7933, 17521, 17521, 17521, 17521,\n",
       "         18394, 17521, 18394, 18394, 18394, 18394, 18394, 18394, 28116,\n",
       "         28116, 28116, 28275, 28275, 28275, 10213, 10213,   315,   315,\n",
       "           315,   315,   315, 15606,   315,   315,   315,   315,   315,\n",
       "         15460, 15460,   315, 12982, 12982,  5465, 12982, 12982, 12982],\n",
       "        [ 2546,  2546,  2546, 18600, 18600, 21638, 21638, 21638, 21638,\n",
       "         15413, 15413,  8068,  8068,  8068,  8068,  8068,  8068,  8691,\n",
       "         24592,  8691,  8691,  8691,  8691,  8691,  8691,  3531,  3531,\n",
       "         17984, 15211, 15211, 15211,  5236, 15211,  5236,  5236,  5236,\n",
       "         22853, 22853, 25234, 25234, 25234, 25234, 25234, 25234, 28436,\n",
       "         28436, 11506, 11506, 11506, 11506, 11506, 26154, 26154, 23428,\n",
       "         23428, 23428, 19163, 19163, 19163, 19163, 19163,  4930,  4930,\n",
       "          4930,  4930, 27581, 27581, 27581,   475,   475, 30738, 30738],\n",
       "        [16042, 16042, 16042, 16042, 23143, 23143, 23143, 23143, 23143,\n",
       "          8320,  8320,  8320,  8320, 11501, 11501, 11501, 11501, 11501,\n",
       "          5446, 24461, 24461, 24461, 24461, 10108, 18449, 15210, 15210,\n",
       "         15210, 24461, 24461, 24461, 26260, 26260, 26260, 26260, 26260,\n",
       "         17215,  5674,   595,   595,   595, 14899, 14899, 21855, 21855,\n",
       "         21855, 13366, 13366, 13366, 28961, 28961, 28961, 28961, 13313,\n",
       "         13313, 13313, 13313, 13313, 13313, 22509, 22509, 23536, 23536,\n",
       "         23536, 13474, 13474, 13474,  3606,  3606, 27964, 27964,  2910],\n",
       "        [31672, 15751, 15751, 15751, 15751, 29982, 29982, 29982, 29982,\n",
       "         29982, 29982,  6691,  6691,  6691,  6691, 19202,   804, 11545,\n",
       "         11545, 11545, 29270,  2926,  2926,  2926,  5451,  5451,  5451,\n",
       "          5451, 31389, 31389, 31389, 31389, 31389, 11257, 11257, 11257,\n",
       "         11257, 11257, 11257, 24667, 24667, 11257, 11257, 11257, 11257,\n",
       "         11257, 11257, 11257, 13073, 22261,  4504,  4504,  4504,  4504,\n",
       "          4504,  4504,  4504,  4504,  4504,  7543,  3411,  3411,  3411,\n",
       "          3411, 30503, 29420,  5057,  5057,  5057,  3411,  3411,  3411],\n",
       "        [ 9058,  9058, 22868, 22868, 15289, 15289, 15289,  8739,  8739,\n",
       "          8739, 29285, 15289, 29285, 29285, 29285, 29285, 29285, 11970,\n",
       "         28560, 28560, 11970,  7606,  7421,  7421,  7421,  7421,  7421,\n",
       "          7421, 15289, 15289, 15289, 15289, 15289, 15058, 15058, 15058,\n",
       "         15058, 23060,  2101,  2101, 21165, 21165, 21165, 23172, 23172,\n",
       "         23172, 23172,  6235,  6235,  6235,  6235,  6235,  6235, 21206,\n",
       "         21206, 21206, 21206, 21206, 21206, 23323,  7110,  7110,  7110,\n",
       "          7110,  7110,  7110,  7110, 24070,  4384, 24070, 24070, 11008],\n",
       "        [26688, 26688, 26688, 26688, 26688, 26688, 15001, 15001, 15001,\n",
       "         15001, 15001, 15001, 15001, 15001, 29969, 29969, 29969, 29969,\n",
       "         15062, 15062, 15062,  8506,  8506,  8506,  8506,  8506, 21168,\n",
       "         21168, 21168, 21168, 21168, 21168, 21168,  3161, 20092, 20092,\n",
       "          3161, 15116, 15174, 15174, 15174, 15174, 15174, 15174, 15174,\n",
       "         15174, 15174,  3147,  3147,  3147,  3147,  3147,  5803,  5803,\n",
       "          5803,  5803,  5803, 20483,  6938,  6938,  6938,  6938,  1853,\n",
       "          1853,  9980,  9980,  9980, 21712, 21712, 21712, 21712, 26688],\n",
       "        [28990, 22146, 22146, 22146, 18968, 18968,  4045,  4045,  4045,\n",
       "          4045,  4045,  4045,  4045,  4045, 13103, 13103, 13103, 13103,\n",
       "         13103,  2802,  2802,  2802, 19216, 19216, 19216, 19216, 19216,\n",
       "         19216,   925,   925, 29893, 17624, 17624, 17624, 22910, 17624,\n",
       "         22910, 17624, 22910, 17624, 22910, 22910,  3858,  4879,  4879,\n",
       "          4879,  3858,  3858, 11849, 11849, 11849, 11849, 17702, 17702,\n",
       "         17702, 17702, 19875, 19875, 19875, 19875, 19875, 19875, 10799,\n",
       "         10799, 10799, 10799, 16468,  4941,  4941,  4941, 18317, 18317]],\n",
       "       dtype=int32), 10.373235, 0.0]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:56<00:00,  1.87it/s, accuracy=0.293, cost=4.43]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.382, cost=3.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.302678, training avg acc 0.222450\n",
      "epoch 1, testing avg loss 4.189349, testing avg acc 0.318118\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.372, cost=3.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.90it/s, accuracy=0.392, cost=3.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.922164, training avg acc 0.338953\n",
      "epoch 2, testing avg loss 3.897679, testing avg acc 0.349237\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.41, cost=3.29] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.392, cost=3.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.596194, training avg acc 0.370667\n",
      "epoch 3, testing avg loss 3.688465, testing avg acc 0.371471\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.427, cost=3.01]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.43, cost=3.1]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.390535, training avg acc 0.391880\n",
      "epoch 4, testing avg loss 3.522606, testing avg acc 0.392433\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.415, cost=3.2] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.387, cost=3.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 3.361068, training avg acc 0.393642\n",
      "epoch 5, testing avg loss 3.722209, testing avg acc 0.368587\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:56<00:00,  1.87it/s, accuracy=0.101, cost=8.98] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.134, cost=7.91] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.302588, training avg acc 0.342319\n",
      "epoch 6, testing avg loss 8.954465, testing avg acc 0.111929\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.183, cost=5.33]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.22, cost=4.77] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 6.087609, training avg acc 0.163081\n",
      "epoch 7, testing avg loss 5.464771, testing avg acc 0.188166\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.224, cost=4.76]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.237, cost=4.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 5.021356, training avg acc 0.207217\n",
      "epoch 8, testing avg loss 5.044796, testing avg acc 0.212887\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.242, cost=4.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.269, cost=4.19]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.590934, training avg acc 0.234326\n",
      "epoch 9, testing avg loss 4.772264, testing avg acc 0.230869\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.288, cost=3.99]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.253, cost=4.06]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.266440, training avg acc 0.259077\n",
      "epoch 10, testing avg loss 4.590913, testing avg acc 0.245154\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:56<00:00,  1.87it/s, accuracy=0.312, cost=3.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.28, cost=3.97] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.999550, training avg acc 0.282693\n",
      "epoch 11, testing avg loss 4.439598, testing avg acc 0.259213\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.343, cost=3.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.29, cost=3.89] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.763612, training avg acc 0.306095\n",
      "epoch 12, testing avg loss 4.330343, testing avg acc 0.271054\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.376, cost=3.16]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.28, cost=3.82] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.552918, training avg acc 0.328699\n",
      "epoch 13, testing avg loss 4.241842, testing avg acc 0.280827\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.404, cost=2.92]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.29, cost=3.8]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.362485, training avg acc 0.350712\n",
      "epoch 14, testing avg loss 4.174834, testing avg acc 0.288927\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.434, cost=2.72]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.90it/s, accuracy=0.285, cost=3.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.188715, training avg acc 0.371760\n",
      "epoch 15, testing avg loss 4.147378, testing avg acc 0.295353\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:32<00:00,  1.92it/s, accuracy=0.454, cost=2.54]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.01it/s, accuracy=0.323, cost=3.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.030721, training avg acc 0.391814\n",
      "epoch 16, testing avg loss 4.131205, testing avg acc 0.303598\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:22<00:00,  1.95it/s, accuracy=0.474, cost=2.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.04it/s, accuracy=0.317, cost=3.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 2.895344, training avg acc 0.408909\n",
      "epoch 17, testing avg loss 4.158094, testing avg acc 0.308317\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:22<00:00,  1.95it/s, accuracy=0.486, cost=2.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.99it/s, accuracy=0.312, cost=3.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 2.792875, training avg acc 0.420836\n",
      "epoch 18, testing avg loss 4.193141, testing avg acc 0.303542\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:23<00:00,  1.94it/s, accuracy=0.503, cost=2.2] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.04it/s, accuracy=0.312, cost=3.84]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 2.699239, training avg acc 0.431910\n",
      "epoch 19, testing avg loss 4.220928, testing avg acc 0.314666\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:14<00:00,  1.97it/s, accuracy=0.519, cost=2.08]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.301, cost=4.08]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 2.602577, training avg acc 0.444192\n",
      "epoch 20, testing avg loss 4.252253, testing avg acc 0.311463\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:38<00:00,  1.04it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0557322"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
